<template>
  <el-dialog :title="formData.id?'添加权限':'编辑权限'" :visible="showDialog" @close="close">
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="新增权限点" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code" />
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-form-item label="开启" prop="enVisible">
        <el-switch v-model="formData.enVisible" active-value="1" inactive-value="0" />
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="submit">确定</el-button>
          <el-button size="mini">取消</el-button>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { addPerm, permDetails, updatePerm } from '@/api/permission'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    pid: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      formData: {
        name: '', // 权限名称
        code: '', // 权限标识
        description: '', // 权限描述
        type: null, // 权限类型 1为页面路由权限点, 2为按钮权限点
        pid: null, // 权限点父级id 页面权限点pid值为'0', 按钮权限点值为所属页面权限点的id值
        enVisible: 1 // 0关闭, 1开启
      },
      rules: {
        name: [{ required: true, message: '权限点名字不能为空！', trigger: 'blur' }],
        code: [{ required: true, message: '权限表示不能为空！', trigger: 'blur' }],
        description: [{ required: true, message: '权限点描述不能为空！', trigger: 'blur' }],
        enVisible: [{ required: true, message: '权限点状态不能为空！', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 编辑回显
    async getPermDetails(id) {
      this.formData = await permDetails(id)
    },
    close() {
      this.formData = {
        name: '', // 权限名称
        code: '', // 权限标识
        description: '', // 权限描述
        type: null, // 权限类型 1为页面路由权限点, 2为按钮权限点
        pid: null, // 权限点父级id 页面权限点pid值为'0', 按钮权限点值为所属页面权限点的id值
        enVisible: 1 // 0关闭, 1开启
      }
      this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
    },
    // 确定新增/修改
    async submit() {
      await this.$refs.form.validate()
      //   有id说明是编辑
      if (this.formData.id) {
        await updatePerm(this.formData)
        this.$message.success('修改权限点成功！')
      } else {
        await addPerm({
          ...this.formData,
          pid: this.pid,
          type: this.pid === 0 ? 1 : 2
        })
        this.$message.success('添加权限点成功！')
      }
      this.close()
      this.$emit('updateEvent')
    }
  }
}
</script>
<style scoped>
</style>
